#include "tcpclient.h"
#include "./ui_tcpclient.h"

TcpClient::TcpClient(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::TcpClient)
{
    ui->setupUi(this);

    ui->le_port->setText("8000");
    ui->le_ip->setText("127.0.0.1");
    ui->pbn_disconnect->setEnabled(false);

    // 创建通信的套接字对象
    tcp_ = new QTcpSocket(this);

    // 检测服务器是否回复了数据
    connect(tcp_, &QTcpSocket::readyRead, [=] {
        // 接收服务器发送的数据
        QByteArray recv_msg = tcp_->readAll();
        ui->txe_message->append("服务器Say: " + recv_msg);
    });

    // 检测是否和服务器是否连接成功了
    connect(tcp_, &QTcpSocket::connected, this, [=]() {
        ui->txe_message->append("恭喜, 连接服务器成功!!!");
        status_->setPixmap(QPixmap(":/resources/connect.png").scaled(20, 20));
        ui->pbn_connect->setEnabled(false);
        ui->pbn_disconnect->setEnabled(true);
    });

    // 检测服务器是否和客户端断开了连接
    connect(tcp_, &QTcpSocket::disconnected, this, [=]() {
        ui->txe_message->append("服务器已经断开了连接...");
        ui->pbn_connect->setEnabled(true);
        ui->pbn_disconnect->setEnabled(false);
        status_->setPixmap(
            QPixmap(":/resources/disconnect.png").scaled(20, 20));
    });

    // 设置连接状态的状态栏
    status_ = new QLabel(this);
    status_->setPixmap(QPixmap(":/resources/disconnect.png").scaled(20, 20));
    ui->statusbar->addWidget(new QLabel("连接状态："));
    ui->statusbar->addWidget(status_);
}

TcpClient::~TcpClient()
{
    delete ui;
}

void TcpClient::on_pbn_connect_clicked()
{
    QString ip = ui->le_ip->text();
    unsigned short port = ui->le_port->text().toInt();
    // 连接服务器
    tcp_->connectToHost(QHostAddress(ip), port);
    ui->pbn_connect->setEnabled(false);
    ui->pbn_disconnect->setEnabled(true);
}

void TcpClient::on_pbn_disconnect_clicked()
{
    tcp_->close();
    ui->pbn_connect->setEnabled(true);
    ui->pbn_disconnect->setEnabled(false);
}

void TcpClient::on_pbn_send_message_clicked()
{
    QString send_msg = ui->txe_send_message->toPlainText();
    tcp_->write(send_msg.toUtf8());
    ui->txe_message->append("客户端Say: " + send_msg);
    ui->txe_send_message->clear();
}
